﻿using Jay.Sc2.Bof.Lib.State;

namespace Jay.Sc2.Bof.Lib.Action.Terran
{
	public class ActionProduceMarine : ActionProduceTerran
	{
		public static ActionProduceMarine Instance = new ActionProduceMarine();

		private ActionProduceMarine() : base(25, 50, 0, 1) { }

		public override int AvailableProducer(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			return
				(state.Barracks.AvailableForProduction) +
				(state.BarracksTechLab.AvailableForProduction) +
				(state.BarracksReactor.AvailableForProduction);
		}

		public override bool HaveTechnology(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			return
				(state.Barracks.Total) +
				(state.BarracksTechLab.Total) +
				(state.BarracksReactor.Total) > 0;
		}

		public void OnProductionFinished(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			state.Marine++;
		}

		public override void Execute(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			int fromBarracks = (state.Barracks.AvailableForProduction);
			int fromBarracksTechLab = (state.BarracksTechLab.AvailableForProduction);
			int fromBarracksReactor = (state.BarracksReactor.AvailableForProduction);
			if (fromBarracksReactor > 0)
			{
				base.Execute(bo);
				state.BarracksReactor.Production++;
				;
				bo.AddAction(state.Time + BuildTime, new ActionGeneric("ActionSpawnMarine", (ActionGeneric.ActionExecuteDelegate)delegate(IBuildOrder ibo)
				{
					TerranState ibostate = ibo.State as TerranState;
					ibostate.BarracksReactor.Production--;
					OnProductionFinished(ibo);
				}));
			}
			else if (fromBarracks > 0)
			{
				base.Execute(bo);
				state.Barracks.Production++;
				bo.AddAction(state.Time + BuildTime, new ActionGeneric("ActionSpawnMarine", (ActionGeneric.ActionExecuteDelegate)delegate(IBuildOrder ibo)
				{
					TerranState ibostate = ibo.State as TerranState;
					ibostate.Barracks.Production--;
					OnProductionFinished(ibo);
				}));
			}
			else if (fromBarracksTechLab > 0)
			{
				base.Execute(bo);
				state.BarracksTechLab.Production++;
				bo.AddAction(state.Time + BuildTime, new ActionGeneric("ActionSpawnMarine", (ActionGeneric.ActionExecuteDelegate)delegate(IBuildOrder ibo)
				{
					TerranState ibostate = ibo.State as TerranState;
					ibostate.BarracksTechLab.Production--;
					OnProductionFinished(ibo);
				}));
			}
			else throw new InvalidActionException();
		}


		private IAction[,] m_Requirements;
		public override IAction[,] Requirements
		{
			get
			{
				if (m_Requirements == null)
					m_Requirements = new IAction[,] { { ActionProduceBarracks.Instance } };
				return m_Requirements;
			}
		}

	}
}
